<?php

class Workset_Controller_Action_Helper_ModuleConfig extends Zend_Controller_Action_Helper_Abstract {

    const CONFIG_FOLDER = 'configs';
    const PHP_FORMAT = 'php';
    const INI_FORMAT = 'ini';
    const XML_FORMAT = 'xml';

	private static $_formats = array('php', 'ini', 'xml');

    protected $_format = 'php';

    protected $_actionConfig = array();

    function direct($path, $baseFolder = null, $applicationPath = null) {
        return $this->getConfig($path, $baseFolder, $applicationPath);
    }

    function getConfig($path, $baseFolder = null, $applicationPath = null, $actionParams = array()) {
        if (is_array($path)) {
            $path =  implode(DIRECTORY_SEPARATOR, $path);
        } else {
            $path = trim($path, '\/');
        }
        
        if (null === $applicationPath) {
            $modulePath = $this->getFrontController()->getModuleDirectory();
        } elseif (true === $applicationPath) {
            $modulePath = APPLICATION_PATH;
        } elseif (is_string($applicationPath)) {
            $modulePath = $this->getFrontController()->getModuleDirectory($applicationPath);
        } else {
            throw new Zend_Exception('Undefined module path');
        }

        $format = $this->getFormat();
        $configPath = implode(DIRECTORY_SEPARATOR, array(
            $modulePath, (is_string($baseFolder) ? $baseFolder : self::CONFIG_FOLDER), $path.'.'.$format
        ));

        if (file_exists($configPath)) {
            if ($format == self::PHP_FORMAT && $actionParams) {
                $this->_actionConfig = (array)$actionParams;
            }
            return include($configPath);
        } else {
            return array();
        }
    }

    function setFormat($format) {
		$format = strtolower($format);
		if (!in_array($format, self::$_formats)) {
			throw new Zend_Exception('Undefined config type');
		}
        $this->_format = $format;
        return $this;
    }

    function getFormat() {
        return $this->_format;
    }

}

?>